package org.aplikator.server.persistence.search;

import java.util.logging.Logger;

import org.aplikator.server.util.Configurator;

import com.typesafe.config.Config;

/**
 * @author eskymo
 * 
 *         SearchFactory provides a single instance of search client
 * 
 */
public class SearchFactory {
	private static final Logger LOG = Logger.getLogger(SearchFactory.class
			.getName());
	private static final String SEARCHENGINE = "aplikator.searchEngine";
	private static Search search = init();

	
	/**
	 * 
	 * returns the state of search - if it's enabled or disabled for an application
	 * it's defined in config file
	 * 
	 * @return
	 */
	public static boolean isSearchEnabled() {
		Config config  = Configurator.get().getConfig();
		boolean isSearchEnabled = config.getBoolean(Search.SEARCH_ENABLED);
		return isSearchEnabled;
	}
	
	/**
	 * inits the Search - initializes the driver from configuration
	 * 
	 * @return
	 */
	
	private static Search init() {
		String searchEngine = Configurator.get().getConfig()
				.getString(SEARCHENGINE);
		Search search = null;
		try {
			search = (Search) Class.forName(searchEngine).newInstance();
		} catch (InstantiationException e) {
			LOG.severe(e.getMessage());
		} catch (IllegalAccessException e) {
			LOG.severe(e.getMessage());
		} catch (ClassNotFoundException e) {
			LOG.severe(e.getMessage());
		}
		if (search == null) {
			throw new IllegalStateException(
					"Unable to instantiate searchengine");
		}
		return search;
	}

	/**
	 * gets the Search instance
	 * 
	 * @return
	 */
	public static Search get() {
		return search;
	}

}
